package com.weiyi.mashangzhu.Roomer.Fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Roomer.Activity.MainActivity_R;
import com.weiyi.mashangzhu.Roomer.Adapter.OrderAdapter;
import com.weiyi.mashangzhu.Roomer.Bean.OrderBean;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.listener.OnListChangeListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by dell on 2017/5/6.
 */

public class NewsFragment_R extends Fragment {
    PullToRefreshListView refreshList;
    int p=1;
    List<OrderBean.DataBean> list=new ArrayList<>();
    OrderAdapter orderAdapter=null;
    int status;
    private MainActivity_R mainActivity;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = (MainActivity_R) getActivity();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    @Nullable
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        status = bundle.getInt("title");
        View view = inflater.inflate(R.layout.order_page_list, container, false);
        refreshList = (PullToRefreshListView) view.findViewById(R.id.refresh_list);
        refreshList
                .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                    @Override
                    public void onPullDownToRefresh(
                            PullToRefreshBase<ListView> refreshView) {
                        Log.e("TAG", "onPullDownToRefresh");
                        //这里写下拉刷新的任务
                        new DownGetDataTask().execute();
                    }

                    @Override
                    public void onPullUpToRefresh(
                            PullToRefreshBase<ListView> refreshView) {
                        Log.e("TAG", "onPullUpToRefresh");
                        new UpGetDataTask().execute();
                    }
                });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        init(p, status);
    }


    //    @Override
//    public void onResume() {
//        super.onResume();
////        Log.e("======================","onresume");
////        if (refreshList != null) {
////            Log.e("======================","onresume2");
////            refreshList.setRefreshing(true);
////        }
////        init(p, status);
//        setRefresh();
//    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e("======================","setuservisiblehint");
        if (isVisibleToUser) {
            if (refreshList != null) {
                Log.e("======================","setuservisiblehint2");
                refreshList.setRefreshing(true);
            }
        }
    }

    public void setRefresh() {
        if (refreshList != null) {
            refreshList.setRefreshing(true);

        }
    }

    private void listChange() {
        if (orderAdapter != null) {
            orderAdapter.setOnListChangeListener(new OnListChangeListener() {
                @Override
                public void OnListChange() {

                }
            });
        }
    }

    public void init(final int p, int i) {
        Log.e("ppppppppp","====================="+status);

        OkHttpUtils.get().addParams("token",  SPUtils.get(mainActivity, "token", "") + "")
                .addParams("types", i + "")
                .addParams("pagenum", p + "")
                .url(API.BaseApi_R + API.Order_Api)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        T.showShort(mainActivity, "数据获取失败，请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
//                        showLog(response);
                        loge(response);
//                        Log.e("ppppppppppppppppppppp","====================="+response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("status") == 1) {
                                T.showShort(mainActivity, jsonObject.getString("msg"));
//                                SPUtils.put(CouponActivity.this, "isLogin", "0");
                            } else {
                                Log.e("wwwwww","re="+response);
                                Gson gson = new Gson();
                                OrderBean orderBean = gson.fromJson(response, OrderBean.class);
                                if (p == 1) {
                                    list.clear();
                                    list.addAll(orderBean.getData());
                                    orderAdapter = new OrderAdapter(list, mainActivity);
                                    refreshList.setAdapter(orderAdapter);
                                } else {
                                    list.addAll(orderBean.getData());
                                    orderAdapter.notifyDataSetChanged();
                                }



                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }



                    }
                });


    }

        public   void  loge(String str){
            int max_str_length=2001-TAG.length();
            //大于4000时
            while (str.length()>max_str_length){
                Log.e(TAG, str.substring(0,max_str_length) );
                str=str.substring(max_str_length);
            }
            //剩余部分
            Log.e(TAG, str );
        }
        public static void showLog(String str) {
        str = str.trim();
        int index = 0;
        int maxLength = 4000;
        String finalString;
        while (index < str.length()) {
            if (str.length() <= index + maxLength) {
                finalString = str.substring(index);
            } else {
                finalString = str.substring(index, maxLength);
            }
            index += maxLength;
            Log.e("str============", finalString.trim());
        }
    }

    private class DownGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);


            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            p = 1;
            init(p,status);
            refreshList.onRefreshComplete();
        }
    }

    private class UpGetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            p += 1;
            init(p,status);
            refreshList.onRefreshComplete();
        }
    }
}